package org.jeecg.modules.chg.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.system.vo.SysVarModel;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.NumberToCN;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.common.util.pdf.PrintPdfUtils;
import org.jeecg.config.mybatis.TenantContext;
import org.jeecg.modules.arc.entity.ArcAccount;
import org.jeecg.modules.arc.service.IArcAccountService;
import org.jeecg.modules.arc.service.IBasePeriodService;
import org.jeecg.modules.arc.vo.ArcAccountCusVO;
import org.jeecg.modules.bv.entity.BvSubVouchers;
import org.jeecg.modules.bv.entity.BvVersions;
import org.jeecg.modules.bv.entity.BvVouchers;
import org.jeecg.modules.bv.service.IBvSubVouchersService;
import org.jeecg.modules.bv.service.IBvVersionsService;
import org.jeecg.modules.bv.service.IBvVouchersService;
import org.jeecg.modules.chg.entity.ChgFees;
import org.jeecg.modules.chg.entity.ChgPayments;
import org.jeecg.modules.chg.mapper.ChgFeesMapper;
import org.jeecg.modules.chg.mapper.ChgSubFeesMapper;
import org.jeecg.modules.chg.service.IChgBillService;
import org.jeecg.modules.chg.service.IChgFeesService;
import org.jeecg.modules.chg.service.IChgPaymentsService;
import org.jeecg.modules.chg.service.IChgSubFeesService;
import org.jeecg.modules.chg.vo.ChgFeePrintVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 收费记录
 * @Author: jeecg-boot
 * @Date:   2022-02-21
 * @Version: V1.0
 */
@Service
public class ChgBillServiceImpl extends ServiceImpl<ChgFeesMapper, ChgFees> implements IChgBillService {

	@Autowired
	private ChgFeesMapper chgFeesMapper;
	@Autowired
	private ChgSubFeesMapper chgSubFeesMapper;
	@Autowired
	private IBasePeriodService basePeriodService;
	@Autowired
	private IChgFeesService feesService;
	@Autowired
	private IChgSubFeesService subFeesService;
	@Autowired
	private IChgPaymentsService paymentsService;
	@Autowired
	private IArcAccountService accountService;

	@Autowired
	private IBvVouchersService bvVouchersService;
	@Autowired
	private IBvVersionsService bvVersionsService;
	@Autowired
	private IBvSubVouchersService subVouchersService;

	@Autowired
	private RedisUtil redisUtil;

	@Autowired
	private ISysBaseAPI baseAPI;


	/**创建收据PDF打印*/
	@Override
	@Transactional
	public Result<?> createFeePrintBillSj(JSONObject billData){
		//票据数据
		Result<?> printBillDataRs = printBillData(billData);
		return Result.OK("收费成功");
//		return printFeeBillSj(billData,printBillDataRs);
	}
	/**创建收据PDF打印*/
	//@Override
	public Result<?> printFeeBillSj(JSONObject billData,Result<?> printBillDataRs){
		billData = (JSONObject) JSONObject.parse(JSON.toJSONString(billData));
		//票据格式数据
		String dbCode=billData.getString("dbCode");
		if(oConvertUtils.isEmpty(dbCode)){
			dbCode="fee_print_bill_sj";
		}
		//积木报表套打配置信息
		JSONObject printConfig = getPrintConfig(dbCode);

		if(null != printConfig && printConfig.size()<2){
			return Result.error("无打印模板");
		}

		try {
			ChgFeePrintVo feePrintVo = new ChgFeePrintVo();
			if (printBillDataRs.isSuccess() && null != printBillDataRs.getResult()) {
				List<ChgFeePrintVo> feePrintvoLs = (List<ChgFeePrintVo>) printBillDataRs.getResult();
				if (null != feePrintvoLs && feePrintvoLs.size() > 0) {
					//PDF //A4: 595.0F, 842.0F
					Rectangle pdfPage = new RectangleReadOnly(printConfig.getFloat("areaWidth")
							, printConfig.getFloat("areaHeight"));
					// 创建document对象
					Document documentPdf = new Document(pdfPage, 0f, 0f, 0f, 0f);
					//documentPdf.setMargins(0f,0f,0f,0f);
					ByteArrayOutputStream baos = new ByteArrayOutputStream();
					PdfWriter writer = PdfWriter.getInstance(documentPdf, baos);
					documentPdf.open(); // 打开文档

					//测试多页的
					//if(feePrintvoLs.size()<2){
					//	feePrintvoLs.add(feePrintvoLs.get(0));
					//}

					for (int i = 0; i < feePrintvoLs.size(); i++) {
						feePrintVo = feePrintvoLs.get(i);
						if (i != 0) {
							documentPdf.newPage();
						}
						documentPdf = createPDFDocument(printConfig, documentPdf, feePrintVo,pdfPage);
					}
					documentPdf.close();
					ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
					PDDocument document = PDDocument.load(bais);
					try {
						JSONObject jsonObject = new JSONObject();
						jsonObject.put("printPageWidth", printConfig.getInteger("width"));
						jsonObject.put("printPageHeight", printConfig.getInteger("height"));
						jsonObject.put("printPageType", printConfig.getString("paper"));

						document.save("d:/my_doc.pdf");
						//直接打印--是否打印份数弹框
						PrintPdfUtils.PDFprint(document, "my_sj", jsonObject);

						if(null !=feePrintVo.getIsNew()){
							billData.put("isNew",feePrintVo.getIsNew());
						}else{
							billData.put("isNew",true);
						}

						//打印确认处理
						return printBillSubmitPdf(billData,feePrintvoLs);
					} catch (Exception e) {
						e.printStackTrace();
					} finally {
						if (documentPdf != null) {
							try {
								documentPdf.close();
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
						if (document != null) {
							try {
								document.close();
							} catch (IOException e) {
								e.printStackTrace();
							}
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return Result.error("打印异常");
	}

	/**返回积木报表套打行数列数、行高、列宽、套打背景图片大小、纸张大小 等*/
	@Override
	public JSONObject getPrintConfig(String dbCode) {
		JSONObject printConfigObj=new JSONObject();
		float[] colWidth = null;
		float[] rowHeight = null;
		//float []rowHei=null;
		Float areaWidth = new Float(0);
		Float areaHeight = new Float(0);
		JSONObject mergesObj = new JSONObject();

		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		String tenant = TenantContext.getTenant();
		tenant=sysUser.getRelTenantIds().split(",")[0];

		List<Map<String, Object>> jimuReport = bvVouchersService.getJimuReport(dbCode,tenant);
		if (null != jimuReport && jimuReport.size() > 0) {
			Map<String, Object> stringObjectMap = jimuReport.get(0);

			JSONObject jimuObj = (JSONObject) JSONObject.parse(JSON.toJSONString(stringObjectMap));
			JSONObject jsonStrObj = (JSONObject) JSONObject.parse(jimuObj.getString("json_str"));

			//保存每行行高
			JSONObject rowsObj = (JSONObject) jsonStrObj.get("rows");
			Set<String> rowKeys = rowsObj.keySet();
			Iterator<String> iterator = rowKeys.iterator();
			rowHeight = new float[rowKeys.size()];
			while (iterator.hasNext()) {
				String key = (String) iterator.next();
				if (oConvertUtils.isNotEmpty(key) && !"len".equals(key)) {
					JSONObject rowObj = (JSONObject) rowsObj.get(key);
					if (null != rowObj) {
						Float height = rowObj.getFloat("height");
						height = null == height ? 25 : height;
						if (rowHeight.length > Integer.parseInt(key)) {
							rowHeight[Integer.parseInt(key)] = height;
						}
					}
				}
			}
			printConfigObj.put("rowsObj",rowsObj);
			printConfigObj.put("rowHeight",rowHeight);


			//获取当前行列的text --cusCode
			JSONObject rowColTxtObj = new JSONObject();
			JSONObject rowColTxtValObj = new JSONObject();
			iterator = rowKeys.iterator();
			while (iterator.hasNext()) {
				String key = (String) iterator.next();
				if (oConvertUtils.isNotEmpty(key) && !"len".equals(key)) {

					JSONObject rowObj = (JSONObject) rowsObj.get(key);
					if (null != rowObj && rowObj.size()>0) {
						JSONObject cellsObj = (JSONObject) rowObj.get("cells");
						if(null != cellsObj) {
							for (String ckey : cellsObj.keySet()) {
								JSONObject cellObj = (JSONObject) cellsObj.get(ckey);
								if(null != cellObj && cellObj.size()>0){
									//"text":"#{fee_print_bill_sj_ss.cusCode}"
									String text = cellObj.getString("text");
									if(oConvertUtils.isNotEmpty(text) && text.length()>1){
										text=text.replace("#{","");
										text=text.replace("}","");
										if(text.contains(".")){
											String[] txtArr=text.split("\\.");
											rowColTxtValObj.put(key+"_"+ckey,txtArr[1]);
										}else{
											rowColTxtObj.put(key+"_"+ckey,text);
										}
									}
								}
							}
						}
					}
				}
			}
			printConfigObj.put("rowColTxt",rowColTxtObj);
			printConfigObj.put("rowColTxtVal",rowColTxtValObj);

			//保存每列列宽
			JSONObject colsObj = (JSONObject) jsonStrObj.get("cols");
			Set<String> collKeys = colsObj.keySet();
			Iterator<String> collIterator = collKeys.iterator();
			colWidth = new float[collKeys.size() - 1];

			while (collIterator.hasNext()) {
				String key = (String) collIterator.next();
				if (!"len".equals(key)) {
					JSONObject colObj = (JSONObject) colsObj.get(key);
					if (null != colObj) {
						float width = colObj.getFloat("width");
						if (colWidth.length > Integer.parseInt(key)) {
							colWidth[Integer.parseInt(key)] = width;
						}
					}
				}
			}
			printConfigObj.put("colWidth",colWidth);

			////保存每列起始宽 加前一列的宽
			//Float colW=0.0f;
			//colWid=new float[colWidth.length];
			//for (int index=0;index<colWidth.length;index++) {
			//	colW=colW+colWidth[index];
			//	colWid[index]=colW;
			//}
			//
			////保存每行起始高
			//float rowH=0;
			//rowHei=new float[rowHeight.length];
			//for (int index=0;index<rowHeight.length;index++) {
			//	rowH=rowH+rowHeight[index];
			//	rowHei[index]=rowH;
			//}

			//保存单元格的合并列数  A=65
			JSONArray mergesArr = jsonStrObj.getJSONArray("merges");
			for (int i = 0; i < mergesArr.size(); i++) {
				String mergeStr = mergesArr.get(i).toString();//"C2:D2", B9:K9(8,1)
				String[] mSplit = mergeStr.split(":");
				String s0bStr = mSplit[0].substring(0, 1); //C
				String s0eStr = mSplit[0].substring(1);  //2
				String s1bStr = mSplit[1].substring(0, 1); //D
				String s1eStr = mSplit[1].substring(1);  //2
				int c1 = s0bStr.toCharArray()[0] - 65;
				int c2 = s1bStr.toCharArray()[0] - 65;
				int mh = c2 - c1;

				String key = (Integer.parseInt(s0eStr) - 1) + "_" + c1; // row_col 1_2
				mergesObj.put(key, mh);
			}
			printConfigObj.put("merges",mergesObj);

			//获取当前行列的合并后的列索引号
			JSONObject rowColObject = new JSONObject();
			JSONObject rowColMergesWidthObj = new JSONObject();
			for (int i = 0; i < rowHeight.length; i++) {
				int index =-1;
				for (int i1 = 0; i1 < colWidth.length; i1++) {
					String key2= (i)+"_"+(i1);
					if( index >= i1 ){
						rowColObject.put(key2,-1);
					}else{
						index=i1;
						if( null != mergesObj.getInteger(key2) && mergesObj.getInteger(key2)>0){
							index= index + mergesObj.getInteger(key2);

							float mergesWidth=0;
							int i3=0;
							for( int i2=i1;i2<=index;i2++){
								mergesWidth = mergesWidth + colWidth[i1+i3];
								i3++;
							}
							rowColMergesWidthObj.put(key2,mergesWidth);
						}
						rowColObject.put(key2,index);
					}
				}
			}
			printConfigObj.put("rowColIndex",rowColObject);
			printConfigObj.put("rowColMwidth",rowColMergesWidthObj);

			JSONArray imgArr = jsonStrObj.getJSONArray("imgList");
			if (null != imgArr && imgArr.size() > 0) {
				JSONObject imgObj = (JSONObject) imgArr.get(0);
				areaWidth = imgObj.getFloat("width");
				areaHeight = imgObj.getFloat("height");
			}
			printConfigObj.put("areaWidth",areaWidth);
			printConfigObj.put("areaHeight",areaHeight);
			JSONObject printConfig = (JSONObject) jsonStrObj.get("printConfig");
			printConfigObj.put("printConfig",printConfig);
		}
		return printConfigObj;
	}

	/**测试分页*/
	public Document createPDFDocumentTestPage(JSONObject printConfig,Document documentPdf
			,ChgFeePrintVo feePrintVo,Rectangle pdfPage) throws IOException, DocumentException {
		BaseFont bfChinese = BaseFont.createFont("STSong-Light","UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
		Font font = new Font(bfChinese, 12, Font.BOLD);
		Paragraph paragraph = new Paragraph("AAAAA", font); // 创建段落，并设置字体
		paragraph.setAlignment(Paragraph.ALIGN_CENTER); // 设置段落居中
		documentPdf.add(paragraph); // 将段落添加到文档中
		return documentPdf;
	}
	public Document createPDFDocument(JSONObject printConfig,Document documentPdf
			,ChgFeePrintVo feePrintVo,Rectangle pdfPage) throws IOException, DocumentException {
		//PDF //A4: 595.0F, 842.0F

		float[] colWidth = (float[]) printConfig.get("colWidth");
		float[] rowHeight = (float[]) printConfig.get("rowHeight");
		JSONObject rowsObj= (JSONObject) printConfig.get("rowsObj");
		JSONObject mergesObj = (JSONObject) printConfig.get("merges");

		// 创建一个对中文字符集支持的基础字体
		BaseFont bfChinese = BaseFont.createFont("STSong-Light","UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

		// 使用基础字体对象创建新字体对像，粗体12号红色字
		Font font = new Font(bfChinese, 12, Font.BOLD);
		font.setColor(255, 0, 0); //设置文字颜色

		PdfPTable table = new PdfPTable(colWidth.length); // 建立一个14列的空白表格对象
		table.setSpacingBefore(0f); // 设置表格上面空白宽度
		table.setWidthPercentage(colWidth,pdfPage);//设置列宽

		Set<String> rowKeys = rowsObj.keySet();
		Iterator<String> iterator = rowKeys.iterator();
		int rowLen=rowKeys.size();
		for(int index=0;index<rowLen;index++){
			String key = index+"";
			JSONObject rowObj = (JSONObject) rowsObj.get(key);
			if (null != rowObj ) {
				JSONObject cellsObj = (JSONObject) rowObj.get("cells");
				if (null != cellsObj) {
					boolean innerLoop=false;
					JSONObject feeSubObj =null;// (JSONObject) feePrintVo.getFees().get(0);
					for(int cc=0;cc<colWidth.length;cc++){
						String keyCol = cc+"";
						if(null != cellsObj.get(keyCol)) {
							JSONObject colObj = (JSONObject) cellsObj.get(keyCol);
							String text = colObj.getString("text");
							if (oConvertUtils.isNotEmpty(text) && !" ".equals(text)) {
								PdfPCell cell =null;

								/**
								 * {"data":[{"billCode":"1003","serialNum":"7758101","printDate":"2022-03-28"
								 * ,"cusCode":"012019","cusName":"陈福","cusAddr":"丰泽新村10#601","cusPhone":"13678978966"
								 * ,"fees_cusCode":"012016","fees_cusName":"陈福"
								 * ,"beginScale":678.00,"endScale":726.00,"readMonth":"202203","amount":45.00,"totalMoney":128.50
								 * ,"fees_beginScale":678.00,"fees_endScale":726.00,"fees_readMonth":"202203","fees_amount":45.00,"fees_totalMoney":128.50
								 * ,"fees_sfFee":123.58,"fees_penalty":0.00,"fees_wuFee":123.58,"fees_ljFee":123.58
								 * ,"sfFee":123.58,"wuFee":123.58,"ljFee":123.58,"penalty":123.58
								 * ,"moneyCn":"壹佰贰拾叁元伍角捌分整","moneyFee":123.58
								 * ,"fees_moneyCn":"壹佰贰拾叁元伍角捌分整","fees_moneyFee":123.58
								 * ,"otherRemark":"其他备注","fees_otherRemark":"其他备注"
								 * ,"balance":13.83,"preBalance":13.83
								 * ,"fees_balance":13.83,"fees_preBalance":13.83
								 * ,"cashier":"管理员","sysDate":"2022-04-06"
								 * ,"fees_cashier":"管理员","fees_sysDate":"2022-04-06"
								 * }]
								 * }
								 */

								if (text.contains("fee_print_bill_sj_ss.cusCode")) {
									// 建立一个单元格
									//PdfPCell cell=new PdfPCell();
									cell = new PdfPCell(new Paragraph(feePrintVo.getCusCode(),new Font(bfChinese, 10)));
									cell.setHorizontalAlignment(Element.ALIGN_CENTER);
								} else if (text.contains("fee_print_bill_sj_ss.fees_cashier")) {
									cell = new PdfPCell(new Paragraph(feeSubObj.getString("cashier"),
											new Font(bfChinese, 10))); // 建立一个单元格
									cell.setHorizontalAlignment(Element.ALIGN_LEFT);
								} else if (text.contains("fee_print_bill_sj_ss.fees_sysDate")) {
									cell = new PdfPCell(new Paragraph(feePrintVo.getPrintData(),
											new Font(bfChinese, 10))); // 建立一个单元格
									cell.setHorizontalAlignment(Element.ALIGN_LEFT);
								} else if (text.contains("fee_print_bill_sj_ss.cashier")) {
									cell = new PdfPCell(new Paragraph(feeSubObj.getString("cashier"),
											new Font(bfChinese, 10))); // 建立一个单元格
									cell.setHorizontalAlignment(Element.ALIGN_LEFT);
								} else if (text.contains("fee_print_bill_sj_ss.sysDate")) {
									cell = new PdfPCell(new Paragraph(feePrintVo.getPrintData(),
											new Font(bfChinese, 10))); // 建立一个单元格
									cell.setHorizontalAlignment(Element.ALIGN_LEFT);
								} else if (text.contains("fee_print_bill_sj_ss.balance")) {
									cell = new PdfPCell(new Paragraph(feeSubObj.getString("balance"),
											new Font(bfChinese, 10))); // 建立一个单元格
									cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
								} else if (text.contains("fee_print_bill_sj_ss.preBalance")) {
									cell = new PdfPCell(new Paragraph(feeSubObj.getString("preBalance"),
											new Font(bfChinese, 10))); // 建立一个单元格
									cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
								} else if (text.contains("fee_print_bill_sj_ss.fees_balance")) {
									cell = new PdfPCell(new Paragraph(feeSubObj.getString("balance"),
											new Font(bfChinese, 10))); // 建立一个单元格
									cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
								} else if (text.contains("fee_print_bill_sj_ss.fees_preBalance")) {
									cell = new PdfPCell(new Paragraph(feeSubObj.getString("preBalance"),
											new Font(bfChinese, 10))); // 建立一个单元格
									cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
								} else if (text.contains("fee_print_bill_sj_ss.fees_moneyFee")) {
									cell = new PdfPCell(new Paragraph(feePrintVo.getMoneyFee().toString(),
											new Font(bfChinese, 10))); // 建立一个单元格
									cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
								} else if (text.contains("fee_print_bill_sj_ss.moneyFee")) {
									cell = new PdfPCell(new Paragraph(feePrintVo.getMoneyFee().toString(),
											new Font(bfChinese, 10))); // 建立一个单元格
									cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
								} else if (text.contains("fee_print_bill_sj_ss.moneyCn")) {
									cell = new PdfPCell(new Paragraph(feePrintVo.getMoneyCn(),
											new Font(bfChinese, 10))); // 建立一个单元格
									cell.setHorizontalAlignment(Element.ALIGN_LEFT);
								} else if (text.contains("fee_print_bill_sj_ss.fees_moneyCn")) {
									cell = new PdfPCell(new Paragraph(feePrintVo.getMoneyCn(),
											new Font(bfChinese, 10))); // 建立一个单元格
									cell.setHorizontalAlignment(Element.ALIGN_LEFT);
								} else if (text.contains("fee_print_bill_sj_ss.fees_penalty")) {
									cell = new PdfPCell(new Paragraph(feeSubObj.getString("penalty"),
											new Font(bfChinese, 10))); // 建立一个单元格
									cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
								} else if (text.contains("fee_print_bill_sj_ss.fees_sfFee")) {
									cell = new PdfPCell(new Paragraph(feeSubObj.getString("sfFee"),
											new Font(bfChinese, 10))); // 建立一个单元格
									cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
								} else if (text.contains("fee_print_bill_sj_ss.fees_wuFee")) {
									cell = new PdfPCell(new Paragraph(feeSubObj.getString("wuFee"),
											new Font(bfChinese, 10))); // 建立一个单元格
									cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
								} else if (text.contains("fee_print_bill_sj_ss.fees_ljFee")) {
									cell = new PdfPCell(new Paragraph(feeSubObj.getString("ljFee"),
											new Font(bfChinese, 10))); // 建立一个单元格
									cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
								} else if (text.contains("fee_print_bill_sj_ss.penalty")) {
									cell = new PdfPCell(new Paragraph(feeSubObj.getString("penalty"),
											new Font(bfChinese, 10))); // 建立一个单元格
									cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
								} else if (text.contains("fee_print_bill_sj_ss.sfFee")) {
									cell = new PdfPCell(new Paragraph(feeSubObj.getString("sfFee"),
											new Font(bfChinese, 10))); // 建立一个单元格
									cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
								} else if (text.contains("fee_print_bill_sj_ss.wuFee")) {
									cell = new PdfPCell(new Paragraph(feeSubObj.getString("wuFee"),
											new Font(bfChinese, 10))); // 建立一个单元格
									cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
								} else if (text.contains("fee_print_bill_sj_ss.ljFee")) {
									cell = new PdfPCell(new Paragraph(feeSubObj.getString("ljFee"),
											new Font(bfChinese, 10))); // 建立一个单元格
									cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
								} else if (text.contains("fee_print_bill_sj_ss.cusName")) {
									cell = new PdfPCell(new Paragraph(feePrintVo.getCusName(),
											new Font(bfChinese, 10))); // 建立一个单元格
									cell.setHorizontalAlignment(Element.ALIGN_LEFT);
								} else if (text.contains("fee_print_bill_sj_ss.fees_cusCode")) {
									cell = new PdfPCell(new Paragraph(feePrintVo.getCusCode(),
											new Font(bfChinese, 10))); // 建立一个单元格
									cell.setHorizontalAlignment(Element.ALIGN_LEFT);
								} else if (text.contains("fee_print_bill_sj_ss.fees_cusName")) {
									cell = new PdfPCell(new Paragraph(feePrintVo.getCusName(),
											new Font(bfChinese, 10))); // 建立一个单元格
									cell.setHorizontalAlignment(Element.ALIGN_LEFT);
								} else if (text.contains("fee_print_bill_sj_ss.readMonth")) {
									cell = new PdfPCell(new Paragraph(feeSubObj.getString("readMonth"),
											new Font(bfChinese, 10))); // 建立一个单元格
									cell.setHorizontalAlignment(Element.ALIGN_LEFT);
								} else if (text.contains("fee_print_bill_sj_ss.endScale")) {
									cell = new PdfPCell(new Paragraph(feeSubObj.getString("endScale"),
											new Font(bfChinese, 10))); // 建立一个单元格
									cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
								} else if (text.contains("fee_print_bill_sj_ss.amount")) {
									cell = new PdfPCell(new Paragraph( feeSubObj.getString("amount"),
											new Font(bfChinese, 10))); // 建立一个单元格
									cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
								} else if (text.contains("fee_print_bill_sj_ss.totalMoney")) {
									cell = new PdfPCell(new Paragraph(feeSubObj.getString("totalMoney"),
											new Font(bfChinese, 10))); // 建立一个单元格
									cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
								} else if (text.contains("fee_print_bill_sj_ss.fees_endScale")) {
									cell = new PdfPCell(new Paragraph(feeSubObj.getString("endScale"),
											new Font(bfChinese, 10))); // 建立一个单元格
									cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
								} else if (text.contains("fee_print_bill_sj_ss.fees_readMonth")) {
									cell = new PdfPCell(new Paragraph(feeSubObj.getString("readMonth"),
											new Font(bfChinese, 10))); // 建立一个单元格
									cell.setHorizontalAlignment(Element.ALIGN_LEFT);
								} else if (text.contains("fee_print_bill_sj_ss.fees_amount")) {
									cell = new PdfPCell(new Paragraph(feeSubObj.getString("amount"),
											new Font(bfChinese, 10))); // 建立一个单元格
									cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
								} else if (text.contains("fee_print_bill_sj_ss.fees_totalMoney")) {
									cell = new PdfPCell(new Paragraph(feeSubObj.getString("totalMoney"),
											new Font(bfChinese, 10))); // 建立一个单元格
									cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
								} else if (text.contains("上次余额")
										|| text.contains("月份")
										|| text.contains("读数")
										|| text.contains("污水费")
										|| text.contains("水量")
										|| text.contains("水费")
										|| text.contains("违约金")
										|| text.contains("卫生费")
										|| text.contains("合计")
										|| text.contains("现在余额")
								) {
									cell = new PdfPCell(new Paragraph(text,new Font(bfChinese, 10))); // 建立一个单元格
								}else{
									cell = new PdfPCell(new Paragraph("",
											new Font(bfChinese, 10))); // 建立一个单元格
								}

								if(null != cell) {
									// 设置内容水平居中显示
									cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//设置垂直居中
									cell.setFixedHeight(rowHeight[index]);

									String colKey = index + "_" + cc;
									Integer colSpan = mergesObj.getInteger(colKey);
									if (null != colSpan) {
										cell.setColspan(colSpan + 1);
										cc = cc + colSpan;
									}
									cell.setBorder(Rectangle.NO_BORDER);
									table.addCell(cell);
								}
							} else {
								PdfPCell cellSpan = new PdfPCell(new Paragraph("",
										new Font(bfChinese, 10))); // 建立一个单元格
								cellSpan.setHorizontalAlignment(Element.ALIGN_CENTER);
								cellSpan.setVerticalAlignment(Element.ALIGN_MIDDLE);//设置垂直居中
								cellSpan.setBorder(Rectangle.NO_BORDER);
								table.addCell(cellSpan);
							}
						}else{
							PdfPCell cellSpan = new PdfPCell(new Paragraph("",
									new Font(bfChinese, 10))); // 建立一个单元格
							cellSpan.setHorizontalAlignment(Element.ALIGN_CENTER);
							cellSpan.setVerticalAlignment(Element.ALIGN_MIDDLE);//设置垂直居中
							cellSpan.setFixedHeight(rowHeight[index]);
							cellSpan.setBorder(Rectangle.NO_BORDER);
							table.addCell(cellSpan);
						}
					}
				}
			}
		}
		documentPdf.add(table);
		return documentPdf;
	}
	public Document createPDFDocument2(JSONObject printConfig,Document documentPdf
			,ChgFeePrintVo feePrintVo,Rectangle pdfPage) throws IOException, DocumentException {
		//PDF //A4: 595.0F, 842.0F

		float[] colWidth = (float[]) printConfig.get("colWidth");
		float[] rowHeight = (float[]) printConfig.get("rowHeight");
		JSONObject rowsObj= (JSONObject) printConfig.get("rowsObj");
		JSONObject mergesObj = (JSONObject) printConfig.get("merges");

		// 创建一个对中文字符集支持的基础字体
		BaseFont bfChinese = BaseFont.createFont("STSong-Light","UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

		// 使用基础字体对象创建新字体对像，粗体12号红色字
		Font font = new Font(bfChinese, 12, Font.BOLD);
		font.setColor(255, 0, 0); //设置文字颜色

		PdfPTable table = new PdfPTable(colWidth.length); // 建立一个14列的空白表格对象
		table.setSpacingBefore(0f); // 设置表格上面空白宽度
		table.setWidthPercentage(colWidth,pdfPage);//设置列宽

		Set<String> rowKeys = rowsObj.keySet();
		Iterator<String> iterator = rowKeys.iterator();
		int rowLen=rowKeys.size()-1;
		for(int index=0;index<rowLen;index++){
			String key = index+"";
			JSONObject rowObj = (JSONObject) rowsObj.get(key);
			if (null != rowObj ) {
				JSONObject cellsObj = (JSONObject) rowObj.get("cells");
				if (null != cellsObj) {
					boolean innerLoop=false;
					for(int cc=0;cc<colWidth.length;cc++){
						String keyCol = cc+"";
						if(null != cellsObj.get(keyCol)) {
							JSONObject colObj = (JSONObject) cellsObj.get(keyCol);
							String text = colObj.getString("text");
							if (oConvertUtils.isNotEmpty(text) && !" ".equals(text)) {
								PdfPCell cell =null;
								if (text.contains("serialNum")) {
									// 建立一个单元格
									//PdfPCell cell=new PdfPCell();
									cell = new PdfPCell(new Paragraph(feePrintVo.getSerialNum(),new Font(bfChinese, 10)));
									cell.setHorizontalAlignment(Element.ALIGN_CENTER);
								} else if (text.contains("printDate")) {
									cell = new PdfPCell(new Paragraph(feePrintVo.getPrintData(),
											new Font(bfChinese, 10))); // 建立一个单元格
									cell.setHorizontalAlignment(Element.ALIGN_CENTER);
								} else if (text.contains("printDate")) {
									cell = new PdfPCell(new Paragraph(feePrintVo.getPrintData(),
											new Font(bfChinese, 10))); // 建立一个单元格
									cell.setHorizontalAlignment(Element.ALIGN_CENTER);
								} else if (text.contains("billCode")) {
									cell = new PdfPCell(new Paragraph(feePrintVo.getBillCode(),
											new Font(bfChinese, 10))); // 建立一个单元格
									cell.setHorizontalAlignment(Element.ALIGN_CENTER);
								} else if (text.contains("fee_print_bill_sj.cusCode")) {
									cell = new PdfPCell(new Paragraph(feePrintVo.getCusCode(),
											new Font(bfChinese, 10))); // 建立一个单元格
									cell.setHorizontalAlignment(Element.ALIGN_LEFT);
								} else if (text.contains("fee_print_bill_sj.cusName")) {
									cell = new PdfPCell(new Paragraph(feePrintVo.getCusName(),
											new Font(bfChinese, 10))); // 建立一个单元格
									cell.setHorizontalAlignment(Element.ALIGN_LEFT);
								} else if (text.contains("fee_print_bill_sj.cusAddr")) {
									cell = new PdfPCell(new Paragraph(feePrintVo.getCusAddr(),
											new Font(bfChinese, 10))); // 建立一个单元格
									cell.setHorizontalAlignment(Element.ALIGN_LEFT);
								} else if (text.contains("fee_print_bill_sj.cusPhone")) {
									cell = new PdfPCell(new Paragraph(feePrintVo.getCusPhone(),
											new Font(bfChinese, 10))); // 建立一个单元格
									cell.setHorizontalAlignment(Element.ALIGN_LEFT);
								} else if (text.contains("fee_print_bill_sj.otherRemark")) {
									cell = new PdfPCell(new Paragraph("",
											new Font(bfChinese, 10))); // 建立一个单元格
									cell.setHorizontalAlignment(Element.ALIGN_LEFT);
								} else if (text.contains("fee_print_bill_sj.balance")) {
									cell = new PdfPCell(new Paragraph( "现在余额："+feePrintVo.getBalance().toString(),
											new Font(bfChinese, 10))); // 建立一个单元格
									cell.setHorizontalAlignment(Element.ALIGN_LEFT);
								} else if (text.contains("fee_print_bill_sj.moneyCn")) {
									cell = new PdfPCell(new Paragraph(feePrintVo.getMoneyCn(),
											new Font(bfChinese, 10))); // 建立一个单元格
									cell.setHorizontalAlignment(Element.ALIGN_LEFT);
								} else if (text.contains("fee_print_bill_sj.moneyFee")) {
									cell = new PdfPCell(new Paragraph("￥"+feePrintVo.getMoneyFee().toString(),
											new Font(bfChinese, 10))); // 建立一个单元格
									cell.setHorizontalAlignment(Element.ALIGN_LEFT);
								} else if (text.contains("fee_print_bill_sj.cashier")) {
									cell = new PdfPCell(new Paragraph(feePrintVo.getCashier(),
											new Font(bfChinese, 10))); // 建立一个单元格
									cell.setHorizontalAlignment(Element.ALIGN_LEFT);
								} else if (text.contains("fee_print_bill_sj.sysDate")) {
									cell = new PdfPCell(new Paragraph(DateUtils.getDate("yyyy-MM-dd"),
											new Font(bfChinese, 10))); // 建立一个单元格
									cell.setHorizontalAlignment(Element.ALIGN_LEFT);
								} else if (text.contains("fee_print_bill_sj.fees_cusCode")
										|| text.contains("fees_cusCode_left")
										|| text.contains("fee_print_bill_sj.fees_beginScale")
										|| text.contains("fee_print_bill_sj.fees_endScale")
										|| text.contains("fee_print_bill_sj.fees_amount")
										|| text.contains("fee_print_bill_sj.fees_readMonth")
										|| text.contains("fee_print_bill_sj.fees_totalMoney")
										|| text.contains("fee_print_bill_sj.fees_alienMoney")
										|| text.contains("fee_print_bill_sj.fees_penalty")
										|| text.contains("fee_print_bill_sj.fees_money")
										|| text.contains("fees_money_right")
								) {
									if(!innerLoop) {
										//for (int lp = 0; lp < feePrintVo.getFees().size(); lp++) {
										//	List<PdfPCell> pdfCellLs = new ArrayList<>();
										//	JSONObject feeSubObj = (JSONObject) feePrintVo.getFees().get(lp);
										//	PdfPCell cell0 = new PdfPCell(new Paragraph("", new Font(bfChinese, 10))); // 建立一个单元格
										//	int cp=0;
										//	String colKey = index + "_" + cp;
										//	Integer colSpan = mergesObj.getInteger(colKey);
										//	if (null != colSpan) {
										//		cell0.setColspan(colSpan + 1);
										//		cp=cp+colSpan;
										//	}
										//	pdfCellLs.add(cell0);
										//	cp++;
										//
										//	PdfPCell cell1 = new PdfPCell(new Paragraph(feeSubObj.getString("cusCode"),
										//			new Font(bfChinese, 10))); // 建立一个单元格
										//	colKey = index + "_" + cp;
										//	colSpan = mergesObj.getInteger(colKey);
										//	if (null != colSpan) {
										//		cell1.setColspan(colSpan + 1);
										//		cp=cp+colSpan;
										//	}
										//	pdfCellLs.add(cell1);
										//	cp++;
										//
										//	PdfPCell cell2 = new PdfPCell(new Paragraph(feeSubObj.getString("beginScale"),
										//			new Font(bfChinese, 10))); // 建立一个单元格
										//	colKey = index + "_" + cp;
										//	colSpan = mergesObj.getInteger(colKey);
										//	if (null != colSpan) {
										//		cell2.setColspan(colSpan + 1);
										//		cp=cp+colSpan;
										//	}
										//	pdfCellLs.add(cell2);
										//	cp++;
										//	PdfPCell cell3 = new PdfPCell(new Paragraph(feeSubObj.getString("endScale"),
										//			new Font(bfChinese, 10))); // 建立一个单元格
										//	colKey = index + "_" + cp;
										//	colSpan = mergesObj.getInteger(colKey);
										//	if (null != colSpan) {
										//		cell3.setColspan(colSpan + 1);
										//		cp=cp+colSpan;
										//	}
										//	pdfCellLs.add(cell3);
										//	cp++;
										//	PdfPCell cell4 = new PdfPCell(new Paragraph(feeSubObj.getString("readMonth"),
										//			new Font(bfChinese, 10))); // 建立一个单元格
										//	colKey = index + "_" + cp;
										//	colSpan = mergesObj.getInteger(colKey);
										//	if (null != colSpan) {
										//		cell4.setColspan(colSpan + 1);
										//		cp=cp+colSpan;
										//	}
										//	pdfCellLs.add(cell4);
										//	cp++;
										//	PdfPCell cell5 = new PdfPCell(new Paragraph(feeSubObj.getString("amount"),
										//			new Font(bfChinese, 10))); // 建立一个单元格
										//	colKey = index + "_" + cp;
										//	colSpan = mergesObj.getInteger(colKey);
										//	if (null != colSpan) {
										//		cell5.setColspan(colSpan + 1);
										//		cp=cp+colSpan;
										//	}
										//	pdfCellLs.add(cell5);
										//	cp++;
										//	PdfPCell cell6 = new PdfPCell(new Paragraph(feeSubObj.getString("totalMoney"),
										//			new Font(bfChinese, 10))); // 建立一个单元格
										//	colKey = index + "_" + cp;
										//	colSpan = mergesObj.getInteger(colKey);
										//	if (null != colSpan) {
										//		cell6.setColspan(colSpan + 1);
										//		cp=cp+colSpan;
										//	}
										//	pdfCellLs.add(cell6);
										//	cp++;
										//	PdfPCell cell7 = new PdfPCell(new Paragraph(feeSubObj.getString("penalty"),
										//			new Font(bfChinese, 10))); // 建立一个单元格
										//	colKey = index + "_" + cp;
										//	colSpan = mergesObj.getInteger(colKey);
										//	if (null != colSpan) {
										//		cell7.setColspan(colSpan + 1);
										//		cp=cp+colSpan;
										//	}
										//	pdfCellLs.add(cell7);
										//	cp++;
										//	PdfPCell cell8 = new PdfPCell(new Paragraph(feeSubObj.getString("alienMoney"),
										//			new Font(bfChinese, 10))); // 建立一个单元格
										//	colKey = index + "_" + cp;
										//	colSpan = mergesObj.getInteger(colKey);
										//	if (null != colSpan) {
										//		cell8.setColspan(colSpan + 1);
										//		cp=cp+colSpan;
										//	}
										//	pdfCellLs.add(cell8);
										//	cp++;
										//	PdfPCell cell9 = new PdfPCell(new Paragraph(feeSubObj.getString("money"),
										//			new Font(bfChinese, 10))); // 建立一个单元格
										//	colKey = index + "_" + cp;
										//	colSpan = mergesObj.getInteger(colKey);
										//	if (null != colSpan) {
										//		cell9.setColspan(colSpan + 1);
										//		cp=cp+colSpan;
										//	}
										//	pdfCellLs.add(cell9);
										//
										//	for (PdfPCell pdfCellL : pdfCellLs) {
										//		createCellBorder(table, pdfCellL, rowHeight[index]);
										//	}
										//	if(cp<colWidth.length){
										//		for(int b=0;b<colWidth.length-cp;b++) {
										//			PdfPCell tcell = new PdfPCell(new Paragraph("", new Font(bfChinese, 10))); // 建立一
										//			createCellBorder(table, tcell, rowHeight[index]);
										//			cp++;
										//		}
										//	}
										//	cc=cp;
										//}
										innerLoop=true;
										continue;
									}
								} else if (text.contains("用户编号")
										|| text.contains("上次读数")
										|| text.contains("本次读数")
										|| text.contains("抄表月份")
										|| text.contains("水量")
										|| text.contains("水费")
										|| text.contains("违约金")
										|| text.contains("其他费用")
										|| text.contains("费用金额")
								) {
									cell = new PdfPCell(new Paragraph(text,new Font(bfChinese, 10))); // 建立一个单元格
								}else{
									cell = new PdfPCell(new Paragraph("",
											new Font(bfChinese, 10))); // 建立一个单元格
								}

								if(null != cell) {
									// 设置内容水平居中显示
									cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//设置垂直居中
									cell.setFixedHeight(rowHeight[index]);

									String colKey = index + "_" + cc;
									Integer colSpan = mergesObj.getInteger(colKey);
									if (null != colSpan) {
										cell.setColspan(colSpan + 1);
										cc = cc + colSpan;
									}
									cell.setBorder(Rectangle.NO_BORDER);
									table.addCell(cell);
								}
							} else {
								PdfPCell cellSpan = new PdfPCell(new Paragraph("",
										new Font(bfChinese, 10))); // 建立一个单元格
								cellSpan.setHorizontalAlignment(Element.ALIGN_CENTER);
								cellSpan.setVerticalAlignment(Element.ALIGN_MIDDLE);//设置垂直居中
								cellSpan.setBorder(Rectangle.NO_BORDER);
								table.addCell(cellSpan);
							}
						}else{
							PdfPCell cellSpan = new PdfPCell(new Paragraph("",
									new Font(bfChinese, 10))); // 建立一个单元格
							cellSpan.setHorizontalAlignment(Element.ALIGN_CENTER);
							cellSpan.setVerticalAlignment(Element.ALIGN_MIDDLE);//设置垂直居中
							cellSpan.setFixedHeight(rowHeight[index]);
							cellSpan.setBorder(Rectangle.NO_BORDER);
							table.addCell(cellSpan);
						}
					}
				}
			}
		}
		documentPdf.add(table);
		return documentPdf;
	}


	public void createCellBorder(PdfPTable table,PdfPCell cell,float rowHeight){
		// 设置内容水平居中显示
		cell.setHorizontalAlignment(Element.ALIGN_CENTER);
		cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//设置垂直居中
		cell.setFixedHeight(rowHeight);
		cell.setBorder(Rectangle.NO_BORDER);
		table.addCell(cell);
	}

	@Override
	public Result<?> printBillData(JSONObject billData) {
		/***
		 *  accountId: accountId,
		 *           billTypeId: billTypeId,
		 *           feePrintWay: feePrintWay,
		 *           paymentId: paymentId,
		 */
		billData = (JSONObject) JSONObject.parse(JSON.toJSONString(billData));

		SysVarModel isPrintBill = baseAPI.querySysVar("is_print_bill");//是否打印收据
		if(null == isPrintBill || "0".equals(isPrintBill.getValue() )){
			return Result.OK("无打印收据");
		}

		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		String accountId = billData.getString("accountId");
		String accCode = billData.getString("accCode");
		//缴费账户
		ArcAccount arcAccount =null;
		if(oConvertUtils.isNotEmpty(accountId)){
			arcAccount = accountService.getById(accountId);
		}else if(oConvertUtils.isNotEmpty(accCode)){
			List<ArcAccount> accountList = accountService.list(new LambdaQueryWrapper<ArcAccount>()
					.eq(ArcAccount::getCode, accCode)
					.eq(ArcAccount::getDelFlag, 0));
			if(null !=accountList && accountList.size()>0 ){
				arcAccount=accountList.get(0);
				accountId=arcAccount.getId();
			}
		}

		String paymentId = billData.getString("paymentId");
		String billTypeId = billData.getString("billTypeId");
		String feePrintWay = billData.getString("feePrintWay");
		JSONObject userFeeIdJson = null;// (JSONObject) billData.get("userFee");

		List<ChgFeePrintVo> feePrintvoLs = new ArrayList<>();
		//缴费账户对应 用户水表信息
		List<ArcAccountCusVO> cusVOList = accountService.queryAccount(accountId, null,null);
		ArcAccountCusVO cusVO = cusVOList.get(0);

		Map<String,String>cusMap=new HashMap<>();
		for (ArcAccountCusVO accountCusVO : cusVOList) {
			if(!cusMap.containsKey(accountCusVO.getCusId())){
				cusMap.put(accountCusVO.getCusId(),accountCusVO.getCode());
			}
		}
		//当前账号+当前缴费ID缓存10分钟
		String cachePrintVoKey="chg::cache::"+accountId+"::"+paymentId;
		Object cachePrintVoObj = redisUtil.get(cachePrintVoKey);
		if(null != cachePrintVoObj){
			feePrintvoLs= (List<ChgFeePrintVo>) cachePrintVoObj;
			return Result.OK(feePrintvoLs);
		}

		if(null == userFeeIdJson){
			userFeeIdJson=this.getFeeListByPayments(paymentId);
		}

		//当前缴费
		ChgPayments chgPayments = paymentsService.getById(paymentId);

		BvVersions currentVersion = bvVersionsService.getCurrentVersion(billTypeId);
		//BasePeriod basePeriod = basePeriodService.getOne(
		//		new LambdaQueryWrapper<BasePeriod>().eq(BasePeriod::getIsUsed, 1));

		/**
		 *  每户合票	01
		 * 	每户每月	02
		 * 	每表合票	03
		 * 	每表每月	04
		 */


		if ("01".equals(feePrintWay)) {
			//每户合票-会有多个水表用户的
			BigDecimal money = new BigDecimal(0.0);
			JSONArray jsonArray = new JSONArray();
			String financialDate = "";
			String financialMonth = "";
			List<BvSubVouchers> subVouchersLs = new ArrayList<>();

			ChgFees chgFees =null;
			for (ArcAccountCusVO accountCusVO : cusVOList) {

				JSONArray feeIdArray = userFeeIdJson.getJSONArray(accountCusVO.getAccCode());
				if(null != feeIdArray && feeIdArray.size()>0) {
					for (Object o : feeIdArray) {
						//String feeId = o.toString();
						//ChgFees chgFees = feesService.getById(feeId);
						chgFees =(ChgFees)o;

//						if(null != chgFees){
//							feePrintvoLs.add(getFeePrintVoByFees(chgFees,sysUser.getRealname(),chgPayments.getPayFee()));
//						}

//						financialDate = chgFees.getFinancialDate();
//						financialMonth = chgFees.getFinancialMonth();
						money = money.add(chgFees.getMoney());
					}
				}
			}
			//前端打印数据封装
			ChgFeePrintVo feePrintVo = new ChgFeePrintVo();
			if(null != chgFees){
				feePrintVo =getFeePrintVoByFees(chgFees,sysUser.getRealname(),chgPayments.getPayFee(),0);
			}else {
				feePrintVo=getFeePrintVo(chgPayments,chgPayments.getPayFee(),sysUser.getRealname());
			}
			feePrintVo.setIsNew(true);
			//feePrintVo.setFees(jsonArray);

			BvVouchers nextVouchers = bvVouchersService.getNextVouchers("01", currentVersion.getId());
			//currentVersion.setStatus("1");
			nextVouchers.setBillStatusId("02");//占用-采用领用人机制-自己使用
			feePrintVo.setBillCode(nextVouchers.getVoucherNo().intValue() + "");
			feePrintVo.setBillId(nextVouchers.getId());

			nextVouchers.setFinancialDate(new Date());//
			nextVouchers.setBillPrintType(feePrintWay);
			nextVouchers.setBillTypeId(billTypeId);
			nextVouchers.setMoney(money);
			nextVouchers.setOperatedTime(new Date());
			nextVouchers.setReprintTimes(1);
			nextVouchers.setPaymentId(paymentId);
			nextVouchers.setOperatorId(sysUser.getUsername());
			bvVouchersService.updateById(nextVouchers);

			feePrintvoLs.add(feePrintVo);
		}
		else if ("02".equals(feePrintWay)) {
			//每户每月-不管水表用户，按月份分组
			BigDecimal money = new BigDecimal(0.0);
			JSONArray jsonArray = new JSONArray();
			String financialDate = "";
			String financialMonth = "";

			JSONObject feeObj = new JSONObject();

			for (ArcAccountCusVO accItem : cusVOList) {
				JSONArray feeIdArray = userFeeIdJson.getJSONArray(accItem.getCusId());

				for (Object o : feeIdArray) {
					//String feeId = o.toString();
					//ChgFees chgFees = feesService.getById(feeId);
					ChgFees chgFees =(ChgFees)o;
					if (!feeObj.containsKey(chgFees.getFinancialMonth())) {
						JSONArray feeArray = new JSONArray();
						feeArray.add(chgFees);
						feeObj.put(chgFees.getFinancialMonth(), feeArray);
					} else {
						feeObj.getJSONArray(chgFees.getFinancialMonth()).add(chgFees);
					}
				}
			}

			ChgFees chgFees=null;
			for (String key : feeObj.keySet()) {
				//一次key 就是一个月份
				List<BvSubVouchers> subVouchersLs = new ArrayList<>();
				JSONArray feeArray = feeObj.getJSONArray(key);
				for (Object o : feeArray) {
					chgFees = (ChgFees) o;

					financialDate = chgFees.getFinancialDate();
					financialMonth = chgFees.getFinancialMonth();
					money = money.add(chgFees.getMoney());
				}
				//前端打印数据封装
				ChgFeePrintVo feePrintVo = new ChgFeePrintVo();
				if(null != chgFees){
					feePrintVo =getFeePrintVoByFees(chgFees,sysUser.getRealname(),chgPayments.getPayFee(),0);
				}
				else {
					feePrintVo=getFeePrintVo(chgPayments,chgPayments.getPayFee(),sysUser.getRealname());
				}
				BvVouchers nextVouchers = bvVouchersService.getNextVouchers("01", currentVersion.getId());
//				nextVouchers.setBillStatusId("02");//占用-采用领用人机制-自己使用
				feePrintVo.setBillCode(nextVouchers.getVoucherNo().intValue() + "");
				feePrintVo.setBillId(nextVouchers.getId());

				nextVouchers.setFinancialDate(new Date());
				nextVouchers.setBillPrintType(feePrintWay);
				nextVouchers.setBillTypeId(billTypeId);
				nextVouchers.setMoney(money);
				nextVouchers.setOperatedTime(new Date());
				nextVouchers.setReprintTimes(1);
				nextVouchers.setPaymentId(paymentId);
				nextVouchers.setOperatorId(sysUser.getUsername());
				bvVouchersService.updateById(nextVouchers);

				//feePrintVo.setBillCode(chgPayments.getId());
				//feePrintVo.setBillId(chgPayments.getId());

				feePrintVo.setIsNew(true);
				//feePrintVo.setFees(jsonArray);
				feePrintvoLs.add(feePrintVo);
			}
		}
		else if ("03".equals(feePrintWay)) {
			//每表合票-不管月份-按水表用户分组
			String financialDate = "";
			String financialMonth = "";

			for (ArcAccountCusVO accountCusVO : cusVOList) {

				List<BvSubVouchers> subVouchersLs = new ArrayList<>();
				BigDecimal money = new BigDecimal(0.0);
				JSONArray jsonArray = new JSONArray();
				JSONArray feeIdArray = userFeeIdJson.getJSONArray(accountCusVO.getCusId());
				ChgFees chgFees =null;
				if(null != feeIdArray && feeIdArray.size()>0) {

					for (Object o : feeIdArray) {
						//String feeId = o.toString();
						//ChgFees chgFees = feesService.getById(feeId);
						chgFees =(ChgFees)o;

						//JSONObject jsonObject = new JSONObject();
						//jsonObject.put("feeId", chgFees.getId());
						//jsonObject.put("cusId", chgFees.getCusId());
						//jsonObject.put("cusCode", cusMap.get(chgFees.getCusId()));
						//jsonObject.put("beginScale", chgFees.getBeginScale());
						//jsonObject.put("endScale", chgFees.getEndScale());
						//jsonObject.put("readMonth", chgFees.getReadMonth());
						//jsonObject.put("amount", chgFees.getAmount());
						//jsonObject.put("penalty", chgFees.getPenalty());//违约金
						//jsonObject.put("totalMoney", chgFees.getTotalMoney());//水费
						//jsonObject.put("alienMoney", chgFees.getAlienMoney());//杂项金额
						//jsonObject.put("money", chgFees.getMoney());//金额
						//jsonObject.put("sfFee", chgFees.getSfFee());//金额
						//jsonObject.put("wuFee", chgFees.getWuFee());//金额
						//jsonObject.put("zaFee", chgFees.getZaFee());//金额
						//jsonObject.put("jiFee", chgFees.getJiFee());//金额
						//jsonObject.put("ljFee", chgFees.getLjFee());//金额
						//jsonObject.put("vatFee", chgFees.getVatFee());//金额
						//jsonObject.put("balance", chgFees.getPostBalance());//金额
						//jsonObject.put("preBalance", chgFees.getPreBalance());//金额
						//jsonArray.add(jsonObject);
						financialDate = chgFees.getFinancialDate();
						financialMonth = chgFees.getFinancialMonth();
						money = money.add(chgFees.getMoney());
					}
					//前端打印数据封装
					ChgFeePrintVo feePrintVo = new ChgFeePrintVo();
					if(null != chgFees){
						feePrintVo =getFeePrintVoByFees(chgFees,sysUser.getRealname(),chgPayments.getPayFee(),0);
					}else {
						feePrintVo=getFeePrintVo(chgPayments,chgPayments.getPayFee(),sysUser.getRealname());
					}
					//feePrintVo.setFees(jsonArray);

					BvVouchers nextVouchers = bvVouchersService.getNextVouchers("01", currentVersion.getId());
					currentVersion.setStatus("1");
					//nextVouchers.setBillStatusId("02");//占用-采用领用人机制-自己使用
					feePrintVo.setBillCode(nextVouchers.getVoucherNo().intValue() + "");
					feePrintVo.setBillId(nextVouchers.getId());

					nextVouchers.setFinancialDate(new Date());

					nextVouchers.setBillPrintType(feePrintWay);
					nextVouchers.setBillTypeId(billTypeId);
					nextVouchers.setMoney(money);
					nextVouchers.setOperatedTime(new Date());
					nextVouchers.setReprintTimes(1);
					nextVouchers.setPaymentId(paymentId);
					nextVouchers.setOperatorId(sysUser.getUsername());
					bvVouchersService.updateById(nextVouchers);

					//feePrintVo.setBillCode(chgPayments.getId());
					//feePrintVo.setBillId(chgPayments.getId());
					feePrintVo.setIsNew(true);
					//feePrintVo.setFees(jsonArray);
					feePrintvoLs.add(feePrintVo);
				}
			}
		}
		else if ("04".equals(feePrintWay)) {
			//每表每月-考虑水表用户和月份分组
			BigDecimal money = new BigDecimal(0.0);
			JSONArray jsonArray = new JSONArray();
			String financialDate = "";
			String financialMonth = "";

			//月份分组
			JSONObject monthFeeGroupObj = new JSONObject();
			int minReadMonth=209912;

			for (ArcAccountCusVO accItem : cusVOList) {
				JSONArray feeIdArray = userFeeIdJson.getJSONArray(accItem.getCode());
				if(null != feeIdArray && feeIdArray.size()>0) {
					for (Object o : feeIdArray) {
						//String feeId = o.toString();
						//ChgFees chgFees = feesService.getById(feeId);
						ChgFees chgFees =(ChgFees)o;
						if(Integer.parseInt(chgFees.getReadMonth()) < minReadMonth){
							minReadMonth=Integer.parseInt(chgFees.getReadMonth());
						}
						if (!monthFeeGroupObj.containsKey(chgFees.getReadMonth())) {
							JSONArray feeArray = new JSONArray();
							feeArray.add(chgFees);
							monthFeeGroupObj.put(chgFees.getReadMonth(), feeArray);
						} else {
							monthFeeGroupObj.getJSONArray(chgFees.getReadMonth()).add(chgFees);
						}
					}
				}
			}
			ChgFees chgFees =null;
			int printIndex=9;
			for (ArcAccountCusVO accountCusVO : cusVOList) { //每表

				for (String s : monthFeeGroupObj.keySet()) {            //每月 s 即月份

					List<BvSubVouchers> subVouchersLs = new ArrayList<>();
					JSONArray feeArray = monthFeeGroupObj.getJSONArray(s);
					for (Object o : feeArray) {
						chgFees = (ChgFees) o;
						if (!accountCusVO.getCode().equals(chgFees.getCusId())) {
							//不是同一水表
							continue;
						}
						if(null != chgFees){
							if(minReadMonth == Integer.parseInt(chgFees.getReadMonth())){
								printIndex=0;
							}
							ChgFeePrintVo feePrintVo =getFeePrintVoByFees(chgFees,sysUser.getRealname(),chgPayments.getPayFee(),printIndex);

							BvVouchers nextVouchers = bvVouchersService.getNextVouchers("01", currentVersion.getId());
							nextVouchers.setBillStatusId("02");//占用-采用领用人机制-自己使用,,本次多张
							nextVouchers.setFinancialDate(new Date());
							nextVouchers.setBillPrintType(feePrintWay);
							nextVouchers.setBillTypeId(billTypeId);
							nextVouchers.setMoney(chgFees.getMoney());
							nextVouchers.setOperatedTime(new Date());
							nextVouchers.setPaymentId(paymentId);
							nextVouchers.setOperatorId(sysUser.getUsername());
							bvVouchersService.updateById(nextVouchers);

							feePrintVo.setIsNew(true);
							feePrintVo.setBillCode(nextVouchers.getVoucherNo().intValue() + "");
							feePrintVo.setBillId(nextVouchers.getId());
							feePrintVo.setAccountId(accountId);
							feePrintVo.setPaymentId(paymentId);
							feePrintVo.setBillTypeId(billTypeId);
							feePrintVo.setFeePrintWay(feePrintWay);
							//feePrintVo.setFees(jsonArray);
							feePrintvoLs.add(feePrintVo);
							printIndex++;
						}
						money = money.add(chgFees.getMoney());
					}
				}
			}
			if(null == chgFees){
				//前端打印数据封装
				ChgFeePrintVo feePrintVo = new ChgFeePrintVo();
				//feePrintVo.setBillCode(chgPayments.getId());
				//feePrintVo.setBillId(chgPayments.getId());
				//预充值的
				feePrintVo=getFeePrintVo(chgPayments,chgPayments.getPayFee(),sysUser.getRealname());

				BvVouchers nextVouchers = bvVouchersService.getNextVouchers("01", currentVersion.getId());
				nextVouchers.setBillStatusId("02");//占用-采用领用人机制-自己使用 预充值只有一条
				nextVouchers.setFinancialDate(new Date());
				nextVouchers.setBillPrintType(feePrintWay);
				nextVouchers.setBillTypeId(billTypeId);
				nextVouchers.setMoney(money);
				nextVouchers.setOperatedTime(new Date());
				nextVouchers.setPaymentId(paymentId);
				nextVouchers.setOperatorId(sysUser.getUsername());
				bvVouchersService.updateById(nextVouchers);

				feePrintVo.setIsNew(true);
				feePrintVo.setBillCode(nextVouchers.getVoucherNo().intValue() + "");
				feePrintVo.setBillId(nextVouchers.getId());
				feePrintVo.setAccountId(chgPayments.getAccountId());
				feePrintVo.setPaymentId(paymentId);
				feePrintVo.setBillTypeId(billTypeId);
				feePrintVo.setFeePrintWay(feePrintWay);
				feePrintvoLs.add(feePrintVo);
			}
		}
		if(oConvertUtils.isNotEmpty(accountId) && oConvertUtils.isNotEmpty(paymentId)){
			//缓存10分钟
			redisUtil.set(cachePrintVoKey,feePrintvoLs,10*60);
		}
		return Result.OK(feePrintvoLs);
	}


	//封装打印VO
	public ChgFeePrintVo getFeePrintVoByFees(ChgFees chgFees,String cashier,BigDecimal payMoney ,int printIndex){
		ChgFeePrintVo feePrintVo = new ChgFeePrintVo();
		feePrintVo.setCusCode(chgFees.getCusId());
		feePrintVo.setFees_cusCode(chgFees.getCusId());
		feePrintVo.setCusName(chgFees.getCusName());
		feePrintVo.setFees_cusName(chgFees.getCusName());

		feePrintVo.setPreBalance(chgFees.getPreBalance().toString()+"元");
		feePrintVo.setFees_preBalance(chgFees.getPreBalance().toString()+"元");
		feePrintVo.setBalance(chgFees.getPostBalance().toString()+"元");
		feePrintVo.setFees_balance(chgFees.getPostBalance().toString()+"元");

		feePrintVo.setReadMonth(chgFees.getReadMonth());
		feePrintVo.setFees_readMonth(chgFees.getReadMonth());
		feePrintVo.setBeginScale(chgFees.getBeginScale().setScale(0,BigDecimal.ROUND_DOWN).toString());
		feePrintVo.setFees_beginScale(chgFees.getBeginScale().setScale(0,BigDecimal.ROUND_DOWN).toString());
		feePrintVo.setEndScale(chgFees.getEndScale().setScale(0,BigDecimal.ROUND_DOWN).toString());
		feePrintVo.setFees_endScale(chgFees.getEndScale().setScale(0,BigDecimal.ROUND_DOWN).toString());
		feePrintVo.setAmount(chgFees.getAmount().setScale(0,BigDecimal.ROUND_DOWN).toString()+"吨");
		feePrintVo.setFees_amount(chgFees.getAmount().setScale(0,BigDecimal.ROUND_DOWN).toString()+"吨");

		//本期缴
		if(printIndex==0){
			feePrintVo.setPayFee(payMoney.toString()+"元");
			feePrintVo.setFees_payFee(payMoney.toString()+"元");
		}else{
			feePrintVo.setPayFee("0.0元");
			feePrintVo.setFees_payFee("0.0元");
		}

		feePrintVo.setSfFee(chgFees.getTotalMoney().toString()+"元");
		feePrintVo.setFees_sfFee(chgFees.getTotalMoney().toString()+"元");
		feePrintVo.setPenalty(chgFees.getPenalty().toString()+"元");
		feePrintVo.setFees_penalty(chgFees.getPenalty().toString()+"元");
		feePrintVo.setLjFee(chgFees.getLjMoney().toString()+"元");
		feePrintVo.setFees_ljFee(chgFees.getLjMoney().toString()+"元");
		feePrintVo.setWuFee(chgFees.getWuMoney().toString()+"元");
		feePrintVo.setFees_wuFee(chgFees.getWuMoney().toString()+"元");

		feePrintVo.setTotalMoney(chgFees.getMoney().toString()+"元");//合计
		feePrintVo.setFees_totalMoney(chgFees.getMoney().toString()+"元");
		feePrintVo.setMoneyFee(chgFees.getMoney().toString()+"元");//费用数字
		feePrintVo.setFees_moneyFee(chgFees.getMoney()+"元");

		feePrintVo.setMoneyCn(NumberToCN.number2CNMontrayUnit(chgFees.getMoney()));//金额大写
		feePrintVo.setFees_moneyCn(NumberToCN.number2CNMontrayUnit(chgFees.getMoney()));
		feePrintVo.setFeeId(chgFees.getId());
		feePrintVo.setCashier(cashier);
		feePrintVo.setFees_cashier(cashier);
		feePrintVo.setSysDate(DateUtils.getDate("yyyy-MM-dd"));
		feePrintVo.setFees_sysDate(DateUtils.getDate("yyyy-MM-dd"));

		return  feePrintVo;
	}
	public ChgFeePrintVo getFeePrintVo(ChgPayments payments,BigDecimal payMoney,String userName){

		ChgFeePrintVo feePrintVo = new ChgFeePrintVo();

		LambdaQueryWrapper<ChgFees> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(ChgFees::getCusId,payments.getAccCode());
		queryWrapper.eq(ChgFees::getStatus,1);
		queryWrapper.eq(ChgFees::getDelFlag,0);
		queryWrapper.orderByDesc(ChgFees::getReadMonth);

		BigDecimal zero = new BigDecimal(0);

		Page<ChgFees> page = new Page<ChgFees>(1, 5);
		IPage<ChgFees> pageList = feesService.page(page, queryWrapper);
		if(null != pageList && null != pageList.getRecords() && pageList.getRecords().size()>0){
			ChgFees chgFees = pageList.getRecords().get(0);

			feePrintVo.setCusCode(payments.getAccCode());
			feePrintVo.setFees_cusCode(payments.getAccCode());
			feePrintVo.setCusName(chgFees.getCusName());
			feePrintVo.setFees_cusName(chgFees.getCusName());
			feePrintVo.setCashier(userName);
			feePrintVo.setFees_cashier(userName);
			feePrintVo.setSysDate(DateUtils.getDate("yyyy-MM-dd"));
			feePrintVo.setFees_sysDate(DateUtils.getDate("yyyy-MM-dd"));
			feePrintVo.setReadMonth(chgFees.getReadMonth());
			feePrintVo.setFees_readMonth(chgFees.getReadMonth());
			feePrintVo.setEndScale(chgFees.getEndScale().setScale(0,BigDecimal.ROUND_DOWN).toString());
			feePrintVo.setFees_endScale(chgFees.getEndScale().setScale(0,BigDecimal.ROUND_DOWN).toString());
			feePrintVo.setFeeId(chgFees.getId());

			//本次预缴的上次余额= 最后缴水费的（本次余额）
			feePrintVo.setPreBalance(chgFees.getPostBalance().toString()+"元");
			feePrintVo.setFees_preBalance(chgFees.getPostBalance().toString()+"元");
			//现在余额：是当前账号余额
			feePrintVo.setBalance(payments.getPostMoney().toString()+"元");
			feePrintVo.setFees_balance(payments.getPostMoney().toString()+"元");

			feePrintVo.setAmount(zero.toString()+"吨");
			feePrintVo.setFees_amount(zero.toString()+"吨");
			feePrintVo.setSfFee(zero.toString()+"元");
			feePrintVo.setFees_sfFee(zero.toString()+"元");
			feePrintVo.setPenalty(zero.toString()+"元");
			feePrintVo.setFees_penalty(zero.toString()+"元");
			feePrintVo.setLjFee(zero.toString()+"元");
			feePrintVo.setFees_ljFee(zero.toString()+"元");
			feePrintVo.setWuFee(zero.toString()+"元");
			feePrintVo.setFees_wuFee(zero.toString()+"元");

			//本期缴
			feePrintVo.setPayFee(payMoney.toString()+"元");
			feePrintVo.setFees_payFee(payMoney.toString()+"元");
			//合计
			feePrintVo.setTotalMoney(payMoney.toString()+"元");
			feePrintVo.setFees_totalMoney(payMoney.toString()+"元");
			//合计数字
			feePrintVo.setMoneyFee(payMoney.toString()+"元");
			feePrintVo.setFees_moneyFee(payMoney.toString()+"元");

			feePrintVo.setMoneyCn(NumberToCN.number2CNMontrayUnit(payMoney));//金额大写
			feePrintVo.setFees_moneyCn(NumberToCN.number2CNMontrayUnit(payMoney));
		}else{
			feePrintVo.setCusCode(payments.getAccCode());
			feePrintVo.setFees_cusCode(payments.getAccCode());
			feePrintVo.setCusName(payments.getAccName());
			feePrintVo.setFees_cusName(payments.getAccName());
			feePrintVo.setCashier(userName);
			feePrintVo.setFees_cashier(userName);
			feePrintVo.setSysDate(DateUtils.getDate("yyyy-MM-dd"));
			feePrintVo.setFees_sysDate(DateUtils.getDate("yyyy-MM-dd"));
//			feePrintVo.setReadMonth(chgFees.getReadMonth());
//			feePrintVo.setFees_readMonth(chgFees.getReadMonth());
//			feePrintVo.setEndScale(chgFees.getEndScale().setScale(0,BigDecimal.ROUND_DOWN).toString());
//			feePrintVo.setFees_endScale(chgFees.getEndScale().setScale(0,BigDecimal.ROUND_DOWN).toString());

			//本次预缴的上次余额= 最后缴水费的（本次余额）
			feePrintVo.setPreBalance(payments.getPreMoney().toString()+"元");
			feePrintVo.setFees_preBalance(payments.getPreMoney().toString()+"元");
			//现在余额：是当前账号余额
			feePrintVo.setBalance(payments.getPostMoney().toString()+"元");
			feePrintVo.setFees_balance(payments.getPostMoney().toString()+"元");

			feePrintVo.setAmount(zero.toString()+"吨");
			feePrintVo.setFees_amount(zero.toString()+"吨");
			feePrintVo.setSfFee(zero.toString()+"元");
			feePrintVo.setFees_sfFee(zero.toString()+"元");
			feePrintVo.setPenalty(zero.toString()+"元");
			feePrintVo.setFees_penalty(zero.toString()+"元");
			feePrintVo.setLjFee(zero.toString()+"元");
			feePrintVo.setFees_ljFee(zero.toString()+"元");
			feePrintVo.setWuFee(zero.toString()+"元");
			feePrintVo.setFees_wuFee(zero.toString()+"元");

			//本期缴
			feePrintVo.setPayFee(payMoney.toString()+"元");
			feePrintVo.setFees_payFee(payMoney.toString()+"元");
			//合计
			feePrintVo.setTotalMoney(payMoney.toString()+"元");
			feePrintVo.setFees_totalMoney(payMoney.toString()+"元");
			//合计数字
			feePrintVo.setMoneyFee(payMoney.toString()+"元");
			feePrintVo.setFees_moneyFee(payMoney.toString()+"元");

			feePrintVo.setMoneyCn(NumberToCN.number2CNMontrayUnit(payMoney));//金额大写
			feePrintVo.setFees_moneyCn(NumberToCN.number2CNMontrayUnit(payMoney));
		}
		return  feePrintVo;
	}

	//重打已打印的票据
	@Override
	public Result<?> printRepeatBillData(JSONObject billData) {
		/***
		 *  id: billId,
		 *  accCode: accCode
		 */
		billData = (JSONObject) JSONObject.parse(JSON.toJSONString(billData));

		String accountId =null;
		ArcAccount arcAccount =null;
		String accCode = billData.getString("accCode");
		String billId = billData.getString("id");
		BvVouchers vouchers = bvVouchersService.getById(billId);
		if(null == vouchers){
			return Result.error("票据不存在");
		}
		//票据类型
		String billTypeId = vouchers.getBillTypeId();
		//打印方式
		String billPrintType = vouchers.getBillPrintType();
		if(!"03".equals(vouchers.getBillStatusId())){
			return Result.error("票据已不是有效，请重新查询开票");
		}

		SysVarModel isPrintBill = baseAPI.querySysVar("is_print_bill");//是否打印收据
		if(null == isPrintBill || "0".equals(isPrintBill.getValue() )){
			return Result.OK("无打印收据");
		}

		if(oConvertUtils.isNotEmpty(accCode)){
			List<ArcAccount> accountList = accountService.list(new LambdaQueryWrapper<ArcAccount>()
					.eq(ArcAccount::getCode, accCode)
					.eq(ArcAccount::getDelFlag, 0));
			if(null !=accountList && accountList.size()>0 ){
				arcAccount=accountList.get(0);
				accountId=arcAccount.getId();
			}
		}

		List<ArcAccountCusVO> cusVOList = accountService.queryAccount(accountId, null,null);
		ArcAccountCusVO cusVO = cusVOList.get(0);

		Map<String,String>cusMap=new HashMap<>();
		for (ArcAccountCusVO accountCusVO : cusVOList) {
			if(!cusMap.containsKey(accountCusVO.getCusId())){
				cusMap.put(accountCusVO.getCusId(),accountCusVO.getCode());
			}
		}

		String feePrintWay = billData.getString("feePrintWay");

		List<ChgFeePrintVo> feePrintvoLs = new ArrayList<>();


		List<BvSubVouchers> subVouchersLs = subVouchersService.selectByMainId(billId);
		if(null != subVouchersLs && subVouchersLs.size()>0) {
			for (BvSubVouchers subVouchers : subVouchersLs) {
				String printJson = subVouchers.getPrintJson();
				ChgFeePrintVo feePrintVo = JSON.parseObject(printJson, ChgFeePrintVo.class);
				feePrintVo.setPrintData(DateUtils.getDate("yyyy-MM-dd"));
				feePrintVo.setSerialNum(Math.round(Math.random() * 10000000L) + "");

				feePrintVo.setIsNew(false);
				feePrintVo.setBillCode(vouchers.getVoucherNo().intValue() + "");
				feePrintVo.setBillId(vouchers.getId());
				feePrintvoLs.add(feePrintVo);
			}
		}

		return Result.OK(feePrintvoLs);
	}

	/**重打-获取数据并直接打印*/
	@Override
	public Result<?> printRepeatBillDataPdf(JSONObject billData) {
		Result<?> printBillDataRs = printRepeatBillData(billData);
		return printFeeBillSj(billData,printBillDataRs);
	}

	@Override
	@Transactional
	public Result<?> printBillSubmit(JSONObject billData) {

		/***
		 * billId
		 * accountId
		 * paymentId
		 * billTypeId
		 * feePrintWay
		 * printIndex
		 * isPrint
		 * isNew 新开/重打
		 *
		 * 不管什么打印方式，当前只有打印一张票据 feePrintvo
		 * 这个printIndex是定位 当前打印哪一张 printBillData
		 *
		 *
		 */
		billData = (JSONObject) JSONObject.parse(JSON.toJSONString(billData));
		String billId = billData.getString("billId");
		String accountId = billData.getString("accountId");
		Integer printIndex = billData.getInteger("printIndex");
		Boolean isPrint = billData.getBoolean("isPrint");
		Boolean isNew = billData.getBoolean("isNew");
		if(isPrint){
			//确认已打印
			if(isNew) {
				//Set<String> cusIdSet = new HashSet();
				ChgFeePrintVo feePrintvo = null;
				JSONArray feesArray = null;

				Result<?> resultData = this.printBillData(billData);
				if (resultData.isSuccess()) {
					List<ChgFeePrintVo> feePrintvoLs = (List<ChgFeePrintVo>) resultData.getResult();
					feePrintvo = feePrintvoLs.get(printIndex);
				}

				BvVouchers vouchers = bvVouchersService.getById(billId);
				vouchers.setBillStatusId("03");
				//ChgPayments payments = paymentsService.getById(vouchers.getPaymentId());
				//JSONObject userFeeIdJson = getFeeListByPayments(vouchers.getPaymentId());
				////缴费账户对应 用户水表信息
				//List<ArcAccountCusVO> cusVOList = accountService.queryAccount(payments.getAccountId()
				//		, null,null);

				List<BvSubVouchers> subVouchersLs = new ArrayList<>();
				BvSubVouchers subVouchers = new BvSubVouchers();
				subVouchers.setAmount(new BigDecimal(feePrintvo.getAmount()));
				subVouchers.setMoney(new BigDecimal(feePrintvo.getMoneyFee()));
				subVouchers.setChargeId(feePrintvo.getFeeId());
				subVouchers.setAccountId(accountId);
				subVouchers.setPrintJson(JSON.toJSONString(feePrintvo));
				subVouchersLs.add(subVouchers);

				for (BvSubVouchers subVoucher : subVouchersLs) {
					subVoucher.setVoucherId(vouchers.getId());
					subVouchersService.save(subVoucher);
				}
				bvVouchersService.updateById(vouchers);
			}else{
				//重打仅增加打印次数
				BvVouchers vouchers = bvVouchersService.getById(billId);
				vouchers.setReprintTimes(vouchers.getReprintTimes()+1);
				bvVouchersService.updateById(vouchers);
			}
		}else{
			//取消打印
			if(isNew) {
				//票据清空
				BvVouchers vouchers = bvVouchersService.getById(billId);
				vouchers.setBillStatusId("01");
				vouchers.setFinancialDate(null);
				vouchers.setBillPrintType("");
				vouchers.setMoney(new BigDecimal(0.0));
				vouchers.setOperatedTime(null);
				vouchers.setPaymentId("");
				vouchers.setOperatorId("");
				bvVouchersService.updateById(vouchers);

				List<BvSubVouchers> subVouchers = subVouchersService.selectByMainId(vouchers.getId());
				if (null != subVouchers && subVouchers.size() > 0) {
					List<String> collect = subVouchers.stream().map(BvSubVouchers::getId).collect(Collectors.toList());
					subVouchersService.removeByIds(collect);
				}
				return Result.OK("已取消成功");
			}
			//else{
			// //无需操作
			//}
			return Result.OK("已取消成功");
		}
		return Result.OK("已打印成功");
	}

	//PDF方式-打印确认
	@Transactional
	public Result<?> printBillSubmitPdf(JSONObject billData,List<ChgFeePrintVo> feePrintvoLs ) {

		/***
		 * accountId
		 * paymentId
		 * billTypeId
		 * feePrintWay
		 * isPrint
		 * isNew 新开/重打
		 *
		 */
		billData = (JSONObject) JSONObject.parse(JSON.toJSONString(billData));
		String accountId = billData.getString("accountId");
		Boolean isNew = billData.getBoolean("isNew");

		//确认已打印-PDF直接后台打印的
		Set<String> cusIdSet = new HashSet();
		for (int i = 0; i < feePrintvoLs.size(); i++) {
			ChgFeePrintVo feePrintVo = feePrintvoLs.get(i);
			BvVouchers vouchers = bvVouchersService.getById(feePrintVo.getBillId());
			if (isNew) {
				//新开
				//JSONArray feesArray = feePrintVo.getFees();
				//for (Object fee : feesArray) {
				//	JSONObject feeObj = (JSONObject) fee;
				//	cusIdSet.add(feeObj.getString("cusId"));
				//}
				vouchers.setBillStatusId("03");
				List<BvSubVouchers> subVouchersLs = new ArrayList<>();
				//if (null != feesArray) {
				//	for (Object fee : feesArray) {
				//		JSONObject feeObj = (JSONObject) fee;
				//		BvSubVouchers subVouchers = new BvSubVouchers();
				//		subVouchers.setAmount(feeObj.getBigDecimal("amount"));
				//		subVouchers.setMoney(feeObj.getBigDecimal("money"));
				//		subVouchers.setChargeId(feeObj.getString("feeId"));
				//		subVouchers.setAccountId(accountId);
				//		subVouchersLs.add(subVouchers);
				//	}
				//	for (BvSubVouchers subVouchers : subVouchersLs) {
				//		subVouchers.setVoucherId(vouchers.getId());
				//		subVouchersService.save(subVouchers);
				//	}
				//}
				bvVouchersService.updateById(vouchers);
			}else{
				//重打仅增加打印次数
				vouchers.setReprintTimes(vouchers.getReprintTimes()+1);
				bvVouchersService.updateById(vouchers);
			}
		}
		return Result.OK("已打印成功");
	}


	@Override
	public List<ChgFees> noOpenBillFees(String paymentId) {
		return chgFeesMapper.noOpenBillFees(paymentId);
	}

	//补打-作废票据
	@Override
	public Result<?> printVoidBill(JSONObject billData) {
		String billId = billData.getString("id");
		BvVouchers vouchers = bvVouchersService.getById(billId);
		if(null == vouchers){
			return Result.error("票据不存在");
		}

		//票据类型
		String billTypeId = vouchers.getBillTypeId();
		//打印方式
		String billPrintType = vouchers.getBillPrintType();
		if(!"03".equals(vouchers.getBillStatusId())){
			return Result.error("票据已不是有效，请重新查询开票");
		}

		vouchers.setBillStatusId("04");
		bvVouchersService.updateById(vouchers);

		JSONObject rsObj=new JSONObject();
		List<BvSubVouchers> subVouchersLs = subVouchersService.selectByMainId(billId);
		if(null != subVouchersLs && subVouchersLs.size()>0){
			BvSubVouchers subVouchers = subVouchersLs.get(0);
			String chargeId = subVouchers.getChargeId();
			ChgFees fees = feesService.getById(chargeId);
			rsObj.put("paymentId",fees.getPaymentId());
		}

		boolean update = subVouchersService.update(new LambdaUpdateWrapper<BvSubVouchers>()
				.set(BvSubVouchers::getDelFlag, 1)
				.eq(BvSubVouchers::getVoucherId, billId)
				.eq(BvSubVouchers::getDelFlag, 0));

		rsObj.put("billTypeId",billTypeId);
		rsObj.put("feePrintWay",billPrintType);
		return Result.OK(rsObj);
	}


	/**按水表用户分组的收费记录*/
	public JSONObject getFeeListByPayments(String paymentId){
		//用户收费对应ID 过滤已开票据的
		JSONObject userFeeIdJson = new JSONObject();

		List<ChgFees> feesList = noOpenBillFees(paymentId);
		if(null != feesList && feesList.size()>0){
			for (ChgFees chgFees : feesList) {
				if (!userFeeIdJson.containsKey(chgFees.getCusId())) {
					JSONArray jsonArray = new JSONArray();
					jsonArray.add(chgFees);
					userFeeIdJson.put(chgFees.getCusId(), jsonArray);
				} else {
					userFeeIdJson.getJSONArray(chgFees.getCusId()).add(chgFees);
				}
			}
		}
		return userFeeIdJson;
	}


	//批次号
	public String createBatchNo(){
		SimpleDateFormat format = new SimpleDateFormat("yyMMddHHmmss");
		int random = RandomUtils.nextInt(90) + 10;
		String value = format.format(new Date()) + random;
		return value;
	}
}
